package com.song.web;

import com.song.bean.Menu;
import com.song.bean.Role;
import com.song.service.impl.MenuServiceImpl;
import com.song.service.impl.RoleServiceImpl;
import com.song.util.PageUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(urlPatterns = "/power/role/rolemanager")
public class RoleServelet extends HttpServlet {
    private RoleServiceImpl roleService = new RoleServiceImpl();
    private MenuServiceImpl menuService = new MenuServiceImpl();

    /**
     * 根据method的值，判断下一步操作
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if ("select".equals(method)) {
            select(req, resp);
        } else if ("insert_select_menu".equals(method)) {
            insert_select_menu(req, resp);
        } else if ("insert".equals(method)) {
            insert(req, resp);
        } else if ("findById".equals(method)) {
            findById(req, resp);
        } else if ("update".equals(method)) {
            update(req, resp);
        } else if ("findById_update".equals(method)) {
            findById_update(req, resp);
        } else if ("delete".equals(method)) {
            delete(req, resp);

        }
    }

    /**
     * 删除角色
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void delete(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException  {
        //获取要删除角色的ID
        String roleid = req.getParameter("roleid");
        //调用service
        Boolean aBoolean = roleService.deleteRole(Integer.parseInt(roleid));
        if (aBoolean){
            resp.getWriter().println("<script>alert('删除成功');location.href='/power/role/rolemanager?method=select'</script>");
        }else {
            resp.getWriter().println("<script>alert('删除失败');location.href='/power/role/rolemanager?method=select'</script>");
        }
    }

    /**
     * 通过角色ID（roleid）找到角色信息
     * 同时将该角色的菜单初始化，以便于修改角色的菜单权限
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void findById_update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端数据
        System.out.println("======3");
        String roleid = req.getParameter("roleid");
        //调用service
        Role role = roleService.findById_update(Integer.parseInt(roleid));
        //菜单初始化
        List<Menu> menuList = menuService.getMenus();
        if (role != null) {
            req.setAttribute("role", role);
            req.setAttribute("menus", menuList);
            req.getRequestDispatcher("edit.jsp").forward(req, resp);
            System.out.println("======4");
        } else {
            resp.getWriter().println("<script>alert('没有查询到任何信息');location.href='/power/role/list.jsp'</script>");
        }

    }

    /**
     * 修改角色信息
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取修改角色数据
        String roleid = req.getParameter("roleid");
        String roleName = req.getParameter("roleName");
        String[] menuList = req.getParameterValues("menuname");
        String state = req.getParameter("state");

        System.out.println(roleName);
        System.out.println(roleid);
        Role role = null;
        try {
            role = new Role();
            role.setRoleId(Integer.parseInt(roleid));
            role.setRoleName(roleName);
            role.setRoleState(Integer.parseInt(state));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        System.out.println("+--------");

        //调用service
        Integer count = roleService.updateRole(role, menuList);

        /*判断  新增角色对middle数据表影响的行数conut  == 新增角色菜单的个数menuList.length
         * 相等 说明添加成功  不相等 添加失败
         * */
        if (count > 0) {
            resp.getWriter().println("<script>alert('修改成功');location.href='/power/role/rolemanager?method=select'</script>");
        } else {
            resp.getWriter().println("<script>alert('修改失败');location.href='/power/role/rolemanager?method=findById&roleid=roleid'</script>");
        }

    }

    /**
     * 通过角色ID查询角色信息
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void findById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端数据
        String roleid = req.getParameter("roleid");
        //调用service
        Role role = roleService.findById(Integer.parseInt(roleid));
        //菜单初始化
        List<Menu> menuList = menuService.getMenus();
        //角色中的菜单
        List<Menu> roleMenus = role.getMenu();
        System.out.println("=====" + roleMenus.size() + "=====");
        if (role != null) {
            req.setAttribute("role", role);
            req.setAttribute("roleid", roleid);
            req.setAttribute("menus", menuList);
            req.setAttribute("rolemenus", roleMenus);
            req.getRequestDispatcher("edit.jsp").forward(req, resp);
        } else {
            resp.getWriter().println("<script>alert('没有查询到任何信息');location.href='/power/role/list.jsp'</script>");
        }

    }

    /**
     * 新增角色
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void insert(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("======insert");
        //获取新增角色数据
        String roleName = req.getParameter("roleName");
        String[] menuList = req.getParameterValues("menuname");
        String state = req.getParameter("state");
        int roleState = Integer.parseInt(state);

        //调用service
        Integer count = roleService.insertRole(roleName, menuList, roleState);
        /*判断  新增角色对middle数据表影响的行数conut  == 新增角色菜单的个数menuList.length
         * 相等 说明添加成功  不相等 添加失败
         * */
        if (count > 0) {
            resp.getWriter().println("<script>alert('添加成功');location.href='/power/role/rolemanager?method=select'</script>");
        } else {
            resp.getWriter().println("<script>alert('添加失败');location.href='/power/role/rolemanager?method=insert_select_menu'</script>");
        }


    }

    /**
     * 新增角色时，菜单选项的生成
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void insert_select_menu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //调用service
        List<Menu> menuList = menuService.getMenus();
        for (Menu menu : menuList) {
            System.out.println(menu.getMenuName() + menu.getMenuId());
        }
        if (menuList != null) {
            req.setAttribute("menus", menuList);
            req.getRequestDispatcher("add.jsp").forward(req, resp);
        }
    }

    /**
     * 查询（分页）
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void select(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取页面数据
        String index = req.getParameter("index");
        int pageIndex = (index == null || index.length() == 0) ? 1 : Integer.parseInt(index);
        //调用分页工具包
        PageUtils pageUtils = new PageUtils();
        //调用service
        List<Role> roles = roleService.getRoles(pageIndex, pageUtils.getPagesize());
        List<Role> roleList = roleService.getRoles();
        System.out.println(roleList.size());
        pageUtils.setTotal(roleList.size());
        pageUtils.setIndex(pageIndex);
        if (roles != null) {
            req.setAttribute("page", pageUtils);
            req.setAttribute("roles", roles);
            req.getRequestDispatcher("list.jsp").forward(req, resp);
        } else {
            resp.getWriter().println("<script>alert('没有查询到任何信息');location.href='/power/role/list.jsp'</script>");
        }
    }


}
